<script setup lang="ts">
import { useAdConsumption } from "./utils/hook";
import { ref, nextTick, onMounted, onBeforeUnmount } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { deviceDetection, useResizeObserver } from "@pureadmin/utils";
import { ElMessageBox } from "element-plus";

import EditPen from "@iconify-icons/ep/edit-pen";
import Delete from "@iconify-icons/ep/delete";
import Refresh from "@iconify-icons/ep/refresh";
import Plus from "@iconify-icons/ep/plus";
import {hasPerms} from "@/utils/auth";

defineOptions({
  name: "AdConsumption"
});

const formRef = ref();
const tableRef = ref();
const contentRef = ref();

const {
  form,
  loading,
  columns,
  dataList,
  pagination,
  userOptions,
  agentOptions,
  accountOptions,
  adPlanOptions,
  onSearch,
  resetForm,
  getTableList,
  openDialog,
  editRecord,
  deleteRecord,
  handleSizeChange,
  handleCurrentChange
} = useAdConsumption();

onMounted(() => {
  useResizeObserver(contentRef, async () => {
    await nextTick();
  });
  window.addEventListener('keyup', handleEnterKey);
});

onBeforeUnmount(() => {
  window.removeEventListener('keyup', handleEnterKey);
});

const handleEnterKey = (e) => {
  if (e.key === 'Enter') {
    onSearch();
  }
};

/** 删除记录确认 */
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除消耗记录 ID: ${row.id}？`,
    "删除确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(() => {
    deleteRecord(row);
  });
};
</script>

<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto"
    >
      <el-form-item label="投放人员" prop="user_id">
        <el-select
          v-model="form.user_id"
          placeholder="请选择投放人员"
          clearable
          filterable
          class="!w-[150px]"
        >
          <el-option
            v-for="option in userOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="代理商" prop="agent_id">
        <el-select
          v-model="form.agent_id"
          placeholder="请选择代理商"
          clearable
          filterable
          class="!w-[150px]"
        >
          <el-option
            v-for="option in agentOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="广告计划" prop="ad_plan_id">
        <el-select
          v-model="form.ad_plan_id"
          placeholder="请选择计划"
          clearable
          class="!w-[120px]"
        >
          <el-option
            v-for="option in adPlanOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="消耗日期" prop="consumption_date">
        <el-date-picker
          v-model="form.consumption_date"
          type="daterange"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          class="!w-[240px]"
        />
      </el-form-item>

      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="form.keyword"
          placeholder="搜索投放人员或代理商"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          @click="resetForm(formRef)"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <div ref="contentRef" class="flex">
      <PureTableBar
        class="w-full"
        title="广告消耗记录"
        :columns="columns"
        @refresh="onSearch"
      >
        <template #buttons>
          <el-button
            v-if="hasPerms(['assets:btn:add_record'])"
            type="primary"
            :icon="useRenderIcon(Plus)"
            @click="openDialog"
          >
            新增消耗记录
          </el-button>
        </template>

        <template v-slot="{ size, dynamicColumns }">
          <pure-table
            ref="tableRef"
            align-whole="center"
            showOverflowTooltip
            table-layout="auto"
            :loading="loading"
            :size="size"
            adaptive
            :adaptiveConfig="{ offsetBottom: 108 }"
            :data="dataList"
            :columns="dynamicColumns"
            :pagination="{ ...pagination, size }"
            :header-cell-style="{
              background: 'var(--el-fill-color-light)',
              color: 'var(--el-text-color-primary)'
            }"
            @page-size-change="handleSizeChange"
            @page-current-change="handleCurrentChange"
          >
            <template #operation="{ row }">
              <el-button
                v-if="hasPerms(['assets:btn:edit_record'])"
                class="reset-margin"
                link
                type="primary"
                :size="size"
                :icon="useRenderIcon(EditPen)"
                @click="editRecord(row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="hasPerms(['assets:btn:del_record'])"
                class="reset-margin"
                link
                type="danger"
                :size="size"
                :icon="useRenderIcon(Delete)"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </pure-table>
        </template>
      </PureTableBar>
    </div>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}
</style>
